import requests
import re
from bs4 import BeautifulSoup
import execjs
import json
headers={
    'referer':'https://music.163.com/',
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
}

link=input("请输入网易云音乐歌曲的分享链接:")

url='https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token=9df19c4351bd16ecd0fa9e3a2afd49bb'

res=requests.get(url=link,headers=headers).text
soup=BeautifulSoup(res,'html.parser')
id_link=soup.find("link",rel="canonical")
href = id_link.get('href')
id_list = re.findall(r'https://music.163.com/song\?id=(\d+)', href)
music_id = id_list[0]
music_title=soup.find("em",class_="f-ff2").text

print(f"提取到的歌曲ID: {music_id}\n提取到的歌曲名称: {music_title}")

with open('wyy.js', encoding='utf-8') as f:
    js_code = execjs.compile(f.read())
    i3x = {
        "ids": f"[{music_id}]",
        "level": "exhigh",
        "encodeType": "aac",
        "csrf_token": "9df19c4351bd16ecd0fa9e3a2afd49bb"
    }
    r = js_code.call('GetSign',i3x)

    post_url='https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token=9df19c4351bd16ecd0fa9e3a2afd49bb'

    data = {
        "params":r.get("encText"),
        "encSecKey":r.get("encSecKey")
    }
    print(data)
    res1=requests.post(url=post_url,headers=headers,data=data)

    print(res1.text)

    music_download_url=json.loads(res1.text)["data"][0]["url"]

    res2=requests.get(url=music_download_url,headers=headers).content
    with open(f"{music_title}.mp3","wb")as f:
        f.write(res2)